import React, { Component } from 'react';
import styles from './index.less';

// 远程加载js （按需引入）
export function loadFabric() {
  return new Promise(function(resolve, reject) {
    if (window.luckysheet) {
      resolve();
      return;
    }

    var urls = [
      // js
      'https://cdn.jsdelivr.net/npm/fabric@4.1.0',
    ];

    loadjs(urls, {
      async: false,
      success: function() {
        resolve();
      },
    });
  });
}

export default class extends Component {
  componentDidMount = async () => {
    await loadFabric();
    // 创建画布
    const canvas = new fabric.Canvas('canvas-container', {
      width: 3312,
      height: 2877,
      backgroundColor: '#f0f0f0',
    });

    // 添加设计元素
    const rect = new fabric.Rect({
      left: 100,
      top: 100,
      width: 200,
      height: 100,
      fill: 'red',
    });
    canvas.add(rect);

    const text = new fabric.Text('Hello Fabric.js', {
      left: 300,
      top: 300,
      fontSize: 24,
      fill: 'blue',
    });
    canvas.add(text);

    // 支持用户交互
    rect.set({ selectable: true });
    text.set({ selectable: true });

    canvas.on('object:moving', function(e) {
      const obj = e.target;
      // 处理元素拖动事件
      console.log(`移动元素：${obj.type}，left: ${obj.left}, top: ${obj.top}`);
    });
  };
  render() {
    return (
      <div className={styles.container}>
        <canvas id="canvas-container" className={styles.canvas}></canvas>
      </div>
    );
  }
}
